package com.group.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.group.dao.GeneralBeanDao;
import com.group.model.WeiBo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;


import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

@Service
public class WeiBoUtils {
    private static final Logger logger = LoggerFactory.getLogger(WeiBoUtils.class);

    @Autowired
    GeneralBeanDao beanDao;

    /**
     * 根据accessToken获取数据并存入到数据库
     *
     */
    //@Scheduled(initialDelay = WeiBoConf.delay, fixedRate = 1000 * 300)
    public void handleInputWeiBo() throws ParseException {
        List<JSONObject> list = new ArrayList<>();
        String accessToken = WeiBoConf.accessToken;
        String url = "https://api.weibo.com/2/statuses/home_timeline.json?access_token=" + accessToken + "&count=100";
        //第一页
        String firstStringData = WeiXinUtils.get(url);
        JSONObject firstJsonData = JSONObject.parseObject(firstStringData);
        list.add(firstJsonData);
        //返回微博总数量
        int totalNumber = firstJsonData.getInteger("total_number");
        //当有超过100条微博时，返回第二页的数据
        if (totalNumber > 100) {
            JSONArray array = firstJsonData.getJSONArray("statuses");
            int number = array.size() - 1;
            //微博字符串ID
            String idstr = array.getJSONObject(number).getString("idstr");
            //新URL中的max_id参数
            long max_id = Long.parseLong(idstr);
            String newUrl = url + "&max_id=" + max_id;
            //第二页
            String secondStringData = WeiXinUtils.get(newUrl);
            JSONObject secondJsonData = JSONObject.parseObject(secondStringData);
            list.add(secondJsonData);
        }
        for (JSONObject jsonObject : list) {
            WeiBo weiBo = null;
            JSONArray array = jsonObject.getJSONArray("statuses");
            for (int i = 0; i < array.size(); i++) {
                String idstr = array.getJSONObject(i).getString("idstr");
                //查询数据库中属否已存在某条微博
                weiBo = beanDao.quickQueryOne(WeiBo.class, "weiboId", idstr);
                if (weiBo == null) {
                    weiBo = new WeiBo();
                    //微博信息
                    JSONObject jobWeibo = array.getJSONObject(i);
                    String str = jobWeibo.getString("created_at");
                    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
                    //微博创建日期
                    Date createAt = sdf.parse(str);
                    weiBo.setCreateAt(createAt);
                    weiBo.setWeiboId(jobWeibo.getString("idstr"));
                    weiBo.setText(jobWeibo.getString("text"));
                    //微博配图数组
                    JSONArray arrayPicurls = jobWeibo.getJSONArray("pic_urls");
                    weiBo.setThumbnailPic(joinString(arrayPicurls, "thumbnail"));
                    weiBo.setBmiddlePic(joinString(arrayPicurls, "bmiddle"));
                    weiBo.setOriginalPic(joinString(arrayPicurls, "large"));
                    JSONObject jobUser = jobWeibo.getJSONObject("user");
                    weiBo.setUserName(jobUser.getString("name"));
                    beanDao.save(weiBo);

                }

            }

        }

    }


    /**
     * 拼接字符串，用逗号分开，并转换图片地址
     *
     * @param array
     * @param str
     * @return str1
     */
    public String joinString(JSONArray array, String str) {
        if (array == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < array.size(); i++) {
            if (sb.length() > 0) {//该步即不会第一位有逗号，也防止最后一位拼接逗号！
                sb.append(",");
            }
            String string = array.getJSONObject(i).getString("thumbnail_pic").replaceAll("thumbnail", str);
            sb.append(string);

        }

        return sb.toString();
    }


}





